package com.cs.base.util;


import android.os.Build;

import androidx.annotation.RequiresApi;

import java.io.UnsupportedEncodingException;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES加解密工具
 */
public class AESUtil {

    private static final String cipherMode = "AES/CBC/PKCS5Padding";

    private static final String EncryptAlg = "AES";

    private static final String Encode = "UTF-8";

    private static final String defaultKey = "";

    private static final String defaultIV = "";

    /**
     * 创建密钥
     * @return
     */
    private static SecretKeySpec createKey() {
        try {
            byte[] data = defaultKey.getBytes(Encode);
            return new SecretKeySpec(data, EncryptAlg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建16位向量: 不够则用0填充
     * @return
     */
    private static IvParameterSpec createIV() {
        byte[] data = null;
        try {
            data = defaultIV.getBytes(Encode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new IvParameterSpec(data);
    }

    /**
     * 加密：有向量16位，结果转base64
     * @param strToEncode
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String encrypt(String strToEncode) {
        try {
            byte[] content = strToEncode.getBytes(Encode);
            SecretKeySpec key = createKey();
            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key, createIV());
            byte[] data = cipher.doFinal(content);
            return Base64.getEncoder().encodeToString(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param strToDecode
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    public static String decrypt(String strToDecode) {
        try {
            byte[] data = Base64.getDecoder().decode(strToDecode);
            SecretKeySpec key = createKey();
            Cipher cipher = Cipher.getInstance(cipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key, createIV());
            byte[] content = cipher.doFinal(data);
            return new String(content, Encode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}